/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ClasificacionDePizzasMorphologicalDilationBox.java
 *
 * Created on 09-ene-2010, 18:48:12
 */
package clasificaciondepizzas;

import clasificaciondepizzas.models.SauceAndToppingModel;
import clasificaciondepizzas.operations.ImageOperations;
import com.sun.media.jai.widget.DisplayJAI;
import javax.media.jai.PlanarImage;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

/**
 *
 * @author Manuel
 */
public class ClasificacionDePizzasMorphologicalDilationBox extends javax.swing.JDialog {

    /** Creates new form ClasificacionDePizzasMorphologicalDilationBox */
    public ClasificacionDePizzasMorphologicalDilationBox(java.awt.Frame parent) {
        super(parent);
        initComponents();
    }

    public void showSmoothBox() {
        JFrame mainFrame = ClasificacionDePizzasApp.getApplication().getMainFrame();
        smoothBox = new ClasificacionDePizzasSmoothBox(mainFrame);
        smoothBox.setLocationRelativeTo(this);
        image = ImageOperations.dilate(image, dilateSlider.getValue());
        // TODO
        // image = ImageOperations.binarize(image, 2.);
        smoothBox.setImage(image);
        smoothBox.setSauceAndToppingModel(stm);

        ClasificacionDePizzasApp.getApplication().show(smoothBox);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        dilatedImageScrollPane = new javax.swing.JScrollPane();
        acceptButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        dilateSlider = new javax.swing.JSlider();
        sizeTextField = new javax.swing.JTextField();
        sizeLabel = new javax.swing.JLabel();

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(clasificaciondepizzas.ClasificacionDePizzasApp.class).getContext().getResourceMap(ClasificacionDePizzasMorphologicalDilationBox.class);
        setTitle(resourceMap.getString("morphologicalDilationBox.title")); // NOI18N
        setModal(true);
        setName("morphologicalDilationBox"); // NOI18N

        dilatedImageScrollPane.setViewportBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("dilatedImageScrollPane.viewportBorder.title"))); // NOI18N
        dilatedImageScrollPane.setName("dilatedImageScrollPane"); // NOI18N

        acceptButton.setText(resourceMap.getString("acceptButton.text")); // NOI18N
        acceptButton.setName("acceptButton"); // NOI18N
        acceptButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                acceptButtonActionPerformed(evt);
            }
        });

        cancelButton.setText(resourceMap.getString("cancelButton.text")); // NOI18N
        cancelButton.setName("cancelButton"); // NOI18N
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        dilateSlider.setMajorTickSpacing(10);
        dilateSlider.setMaximum(10);
        dilateSlider.setMinimum(3);
        dilateSlider.setMinorTickSpacing(1);
        dilateSlider.setPaintLabels(true);
        dilateSlider.setSnapToTicks(true);
        dilateSlider.setValue(3);
        dilateSlider.setName("dilateSlider"); // NOI18N
        dilateSlider.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                dilateSliderStateChanged(evt);
            }
        });

        sizeTextField.setText(((Integer)dilateSlider.getValue()).toString());
        sizeTextField.setName("sizeTextField"); // NOI18N
        sizeTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sizeTextFieldActionPerformed(evt);
            }
        });

        sizeLabel.setText(resourceMap.getString("sizeLabel.text")); // NOI18N
        sizeLabel.setName("sizeLabel"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(dilatedImageScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(acceptButton, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(cancelButton, javax.swing.GroupLayout.Alignment.TRAILING)))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(dilateSlider, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(sizeLabel)
                                .addGap(30, 30, 30))
                            .addComponent(sizeTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 75, Short.MAX_VALUE))))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {acceptButton, cancelButton});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(dilatedImageScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(acceptButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cancelButton)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(dilateSlider, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(sizeLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(sizeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void dilateSliderStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_dilateSliderStateChanged
        PlanarImage previewImage;

        sizeTextField.setText(((Integer) dilateSlider.getValue()).toString());

        try {
            // previsualización en miniatura de la dilatación morfológica
            previewImage = ImageOperations.dilate(thumbnail, dilateSlider.getValue());
            DisplayJAI display = new DisplayJAI(previewImage);
            dilatedImageScrollPane.setViewportView(display);
        } catch (IllegalArgumentException e) {
            JOptionPane.showMessageDialog(this,
                    "No es posible aplicar el umbral.",
                    "Error",
                    JOptionPane.ERROR_MESSAGE);
        } catch (RuntimeException e) {
            JOptionPane.showMessageDialog(this,
                    "No es posible previsualizar la imagen.",
                    "Error",
                    JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_dilateSliderStateChanged

    private void sizeTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sizeTextFieldActionPerformed
        PlanarImage previewImage; //previsualización en miniatura con el filtro aplicado
        int value = Integer.parseInt(sizeTextField.getText()); // valor del campo de texto

        // el control de desplazamiento se actualiza junto con el campo de texto
        dilateSlider.setValue(value);

        try {
            // previsualización en miniatura de la dilatación morfológica
            previewImage = ImageOperations.dilate(thumbnail, dilateSlider.getValue());
            DisplayJAI display = new DisplayJAI(previewImage);
            dilatedImageScrollPane.setViewportView(display);
        } catch (IllegalArgumentException e) {
            JOptionPane.showMessageDialog(this,
                    "No es posible aplicar la dilatación.",
                    "Error",
                    JOptionPane.ERROR_MESSAGE);
        } catch (RuntimeException e) {
            JOptionPane.showMessageDialog(this,
                    "No es posible previsualizar la imagen.",
                    "Error",
                    JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_sizeTextFieldActionPerformed

    private void acceptButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_acceptButtonActionPerformed
        setVisible(false);
        showSmoothBox();
        dispose();
    }//GEN-LAST:event_acceptButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        dispose();
    }//GEN-LAST:event_cancelButtonActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton acceptButton;
    private javax.swing.JButton cancelButton;
    private javax.swing.JSlider dilateSlider;
    private javax.swing.JScrollPane dilatedImageScrollPane;
    private javax.swing.JLabel sizeLabel;
    private javax.swing.JTextField sizeTextField;
    // End of variables declaration//GEN-END:variables
    private PlanarImage image;
    private PlanarImage thumbnail;
    private ClasificacionDePizzasSmoothBox smoothBox;
    private SauceAndToppingModel stm;

    void setImage(PlanarImage image) {
        this.image = image;
        thumbnail = this.image;
        PlanarImage previewImage; //previsualización en miniatura con el filtro aplicado

        // si la imagen supera el tamaño del panel con desplazamiento se escala a un tamaño menor
        if (image.getWidth() > dilatedImageScrollPane.getWidth() || image.getHeight() > dilatedImageScrollPane.getHeight()) {
            // si la imagen supera la anchura del panel con desplazamiento se escala a una anchura menor
            if (image.getWidth() > image.getHeight()) {
                float ratio = (float) dilatedImageScrollPane.getWidth() / (float) image.getWidth();
                thumbnail = ImageOperations.scale(image, ratio, ratio);
            } // si la imagen supera la altura del panel con desplazamiento se escala a una altura menor
            else {
                float ratio = (float) dilatedImageScrollPane.getHeight() / (float) image.getHeight();
                thumbnail = ImageOperations.scale(image, ratio, ratio);
            }
        }

        try {
            // previsualización en miniatura de la dilatación morfológica
            previewImage = ImageOperations.dilate(thumbnail, dilateSlider.getValue());
            DisplayJAI display = new DisplayJAI(previewImage);
            dilatedImageScrollPane.setViewportView(display);
        } catch (IllegalArgumentException e) {
            JOptionPane.showMessageDialog(this,
                    "No es posible aplicar la dilatación morfológica.",
                    "Error",
                    JOptionPane.ERROR_MESSAGE);
        } catch (RuntimeException e) {
            JOptionPane.showMessageDialog(this,
                    "No es posible previsualizar la imagen.",
                    "Error",
                    JOptionPane.ERROR_MESSAGE);
        }
    }

    void setSauceAndToppingModel(SauceAndToppingModel stm) {
        this.stm = stm;
    }
}
